package com.yt.order.provider.service.impl;

import com.yt.core.service.GenericServiceImpl;
import com.yt.order.api.interfaces.OrderNumberService;
import com.yt.order.api.model.OrderNumber;
import com.yt.order.api.utils.OrderConstants;
import com.yt.order.provider.dao.OrderNumberDao;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by liujunshi on 15-12-30.
 */
public class OrderNumberServiceImpl extends GenericServiceImpl<OrderNumber, Long> implements OrderNumberService {
	private OrderNumberDao dao;

	public OrderNumberServiceImpl(OrderNumberDao dao) {
		super(dao);
		this.dao = dao;
	}

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

	private static DecimalFormat df = new DecimalFormat("00000");

	/**
	 * 获取一个订单编号ID
	 *
	 * @return long
	 */
	private String nextUniqueOrderNumber(Date date, int orderFrom, int orderType) {
		return nextUniqueOrderNumber("00", date, orderFrom, orderType);
	}

	/**
	 * 获取一个订单编号ID
	 *
	 * @return long
	 */
	private String nextUniqueOrderNumber(String prefix, Date date, int orderFrom, int orderType) {
		String dateString = sdf.format(date == null ? new Date() : date);
		long id = getNextBlock(date);
		return prefix + dateString + orderFrom + orderType + df.format(id);
	}

	private String getTodayDate(Date date) {
		if (date == null) {
			date = new Date();
		}
		return sdf.format(date);
	}

	/**
	 * ID申请逻辑方法
	 */
	private Long getNextBlock(Date date) {
		Long todayDate = Long.parseLong(getTodayDate(date));
		OrderNumber orderNumber = dao.get(todayDate);
		if (orderNumber != null) {
			orderNumber.setOrderNumberIndex(orderNumber.getOrderNumberIndex() + 1);
			dao.update(orderNumber);
			return orderNumber.getOrderNumberIndex();
		} else {
			orderNumber = new OrderNumber();
			orderNumber.setOrderDate(todayDate);
			orderNumber.setOrderNumberIndex(1l);
			dao.insert(orderNumber);
			return 1l;
		}
	}

	@Override
	public String nextOrderNumber(int orderFrom, int orderType) {
		return nextUniqueOrderNumber(null, orderFrom, orderType);
	}

	@Override
	public String nextOrderNumber(Date date, int orderFrom, int orderType) {
		return nextUniqueOrderNumber(date, orderFrom, orderType);
	}

	@Override
	public String nextAppOrderNumber(Date date) {
		return nextUniqueOrderNumber("A0", date, OrderConstants.OrderFrom.APP.getValue(), OrderConstants.OrderType.Single.getType());
	}
}
